package cn.tsinghua.comsmacitccntsinghua.utils;

import android.os.Environment;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import okhttp3.ResponseBody;

/**
 * @Author yjl
 * @create 2021/10/15 9:37
 */
public class FileUtil {

    public static boolean writeFile(ResponseBody responseBody){
        File APKFile = new File(Environment.getExternalStorageDirectory().getAbsoluteFile() + "/patch_signed_7zip.apk");
        InputStream inputStream = null;
        OutputStream outputStream = null;
        byte[] fileReader = new byte[4096];

        try{
            long fileSize = responseBody.contentLength();
            long fileSizeDownloaded = 0;
            inputStream = responseBody.byteStream();
            outputStream = new FileOutputStream(APKFile);

            while (true) {
                int read = inputStream.read(fileReader);
                if(read == -1){
                    break;
                }
                outputStream.write(fileReader,0,read);
                fileSizeDownloaded += read;
            }
            outputStream.flush();
            return true;
        }catch (IOException e){
            return false;
        }finally {
            if(inputStream != null){
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(outputStream != null){
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

}
